/*
 * @Date: 2022-03-21 09:49:52
 * @LastEditors: zhaoxm
 * @LastEditTime: 2022-09-13 13:42:12
 * @Description:
 */
import { cloneDeep, isObject } from "lodash"
import { findArrayItem } from "@/utils/tree"

/**
 * @description: 下载blob类型文件
 * @param { Object } res 完整响应体参数
 * @param { Boolean } isAutoDownload 是否自动下载文件
 * @return { Promise<Function> }
 */
export const downLoadBlob = (response, isAutoDownload) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(response.data)
    fileReader.addEventListener("load", (event) => {
      const id = "download-file"
      const oDownLoadFileElement = document.querySelector(id)
      if (oDownLoadFileElement) oDownLoadFileElement.remove()

      const a = document.createElement("a")
      a.id = id
      a.download = window.decodeURI(
        response.headers["content-disposition"]?.split("=")[1]
      )
      a.href = event.target.result

      document.body.append(a)
      const download = () => a.click()
      if (isAutoDownload) download()
      resolve(download)
      a.remove()
    })
  })
}

/**
 * @description: 删除为空值的属性返回一个新的对象
 * @param { Object } data
 * @return { Object } data
 */
// eslint-disable-next-line unicorn/prevent-abbreviations
export const removeEmptyParams = (data) => {
  if (!isObject(data))
    return new Error("removeEmptyParams , data 入参 不是一个 object 类型")
  data = cloneDeep(data)
  for (const key of Object.keys(data)) {
    if (!data[key]) delete data[key]
  }
  return data
}

/**
 * @description: 设置options的数据 根据用户传入的 fields 进行映射
 * @param { Array } options
 * @param { Object } fields
 */
export const setOptionsFiled = (options, fields) => {
  if (!fields) return new Error("请传入fields字段")
  findArrayItem(options, item => {
    for (const key in item) {
      if (fields[key]) item[fields[key]] = item[key]
    }
  })
}

/**
 * @description: 把field字段映射城对象
 * @param { String } field
 * @return { Record<string,string> }
 */
export const filedToObject = (field) => {
  if (!field) return ""
  const fields = field.split(",")
  const conversionResultKey = {}
  for (const item of fields) {
    const [oldKey, newKey] = item.split("as")
    conversionResultKey[oldKey.trim()] = newKey.trim()
  }
  return conversionResultKey
}